<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <h2>动态组件</h2>
      <button @click="str = 'child1'">btn1</button>
      <button @click="str = 'child2'">btn2</button>
      <button @click="str = 'child3'">btn3</button>

      <!-- <keep-alive include="child1,child2"> -->
      <!-- <keep-alive :include="/child1|child2/"> -->
      <keep-alive :include="['child1','child2']">
        <component :is="str"></component>
      </keep-alive>
    </div>

    <script src="./Vue3.js"></script>
    <script>
      const { createApp } = Vue;

      let timer;
      const Child1 = {
        name: "child1",
        data() {
          return {
            count: 1,
          };
        },
        template: `
          <div>child1组件 - {{ count }}</div>
        `,
        mounted() {
          console.log("child1组件被重新渲染了");
        },
        beforeUnmount() {
          console.log("child1组件被卸载了");
        },
        activated() {
          timer = setInterval(() => {
            this.count++;
          }, 1000);
        },
        deactivated() {
          console.log(2);
          clearInterval(timer);
        },
      };
      const Child2 = {
        name: "child2",
        template: `
          <div>child2组件</div>
        `,
        mounted() {
          console.log("child2组件被重新渲染了");
        },
        beforeUnmount() {
          console.log("child2组件被卸载了");
        },
      };
      const Child3 = {
        name: "child3",
        template: `
          <div>child3组件</div>
        `,
        mounted() {
          console.log("child3组件被重新渲染了");
        },
        beforeUnmount() {
          console.log("child3组件被卸载了");
        },
      };

      createApp({
        data() {
          return {
            str: "child1",
          };
        },
        components: {
          Child1,
          Child2,
          Child3,
        },
      }).mount("#app");
    </script>
  </body>
</html>
